/*
 * @Author: hongbin
 * @Date: 2021-09-02 17:04:08
 * @LastEditTime: 2021-09-19 14:22:14
 * @Description: 博客评论的请求 评论分两级评论 即博客的评论和评论的评论
 * @FilePath: /hongbin_xyz_web/api/commentApi.ts
 */

import { query, request } from ".";
import { ThumbsState } from "../pages/blog/[id]";
import { RequestBack } from "./types";

//服务端返回的评论 一级评论
export interface IComment {
  _id: string;
  senderId: string; //发送者
  blogId: string; //发送在哪片博客下 方便博客计算有多少条评论
  content: string; //评论内容
  thumbsUp: string[]; // 记录点赞的人
  thumbsDown: string[]; // 记录点踩的人
  violation: boolean; // 评论是否违规
  commentId?: string;
  sender: [
    {
      // 评论人的信息
      _id: string;
      username: string;
      role: number;
    }
  ];
  hasChild: boolean;
  child?: ISecondComment[];
}

export interface ISecondComment extends Omit<IComment, "hasChild" | "child"> {
  reply: IComment["sender"];
  commentId: string;
  at: string;
}

//发布评论所需参数
export interface CommentParams {
  senderId: string; //发送者
  blogId: string; //发送在哪片博客下
  content: string; //评论内容
  commentId?: string; // 二级评论使用
  at?: string; //@xxx 被@用户的id
  replyUser?: string; //后端填充本次请求的 reply 即 @谁
}

export const sendComment = (params: CommentParams) =>
  request<{
    code: number;
    message: string;
    comment: IComment | ISecondComment;
  }>("/sendComment", params);

/**
 * 根据博客id 获取博客的评论列表 默认20条
 */

type TGetCommentByBlog = (params: {
  _id: string;
  limit?: number;
}) => RequestBack<{ code: number; message: string; comments: IComment[] }>;

export const getCommentByBlog: TGetCommentByBlog = ({ _id, limit = 20 }) =>
  query("/getCommentByBlog", { params: { _id, limit } });

export interface ThumbsCommentProps {
  userId: string;
  commentId: string;
  type: ThumbsState;
  second?: boolean;
}

export const thumbsComment = (
  params: ThumbsCommentProps
): Promise<{ data?: { code: number; message: string } }> =>
  request("/thumbsComment", params);

export const cancelThumbsComment: typeof thumbsComment = params =>
  request("/cancelThumbsComment", params);

interface ITransFromThumbsComment {
  userId: string;
  commentId: string;
  second?: boolean;
  from: ThumbsState;
  to: ThumbsState;
}

export const transformThumbsComment = (
  params: ITransFromThumbsComment
): RequestBack<{ message: string; code: number }> =>
  request("/transformThumbsComment", params);
